package com.showsu.editor.utils.remote;

import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.showsu.editor.entity.platform.xhs.AwemeDetailPlatformResult;
import com.showsu.editor.entity.platform.xhs.XhsAwemeDetailResult;
import com.showsu.editor.entity.remote.moreapi.XhsAwemeDetailMoreApiResult;
import com.showsu.editor.enums.SuccessEnum;
import com.showsu.editor.service.IRemoteInterfaceRecordService;
import com.showsu.editor.service.IRemoteInterfaceWarnSmsRecordService;
import com.showsu.editor.utils.Constant;
import com.showsu.editor.utils.GsonFailSafeArrayJsonDeserializer;
import com.showsu.editor.utils.RetryUtils;
import com.showsu.editor.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * @Author: William
 * @Description:
 * @Date: Created in 10:58 上午 2024/1/11
 * @Modified By:
 */
@Slf4j
@Component
public class Boy235Util {

    private static final int timeout = 20000;

    /**
     * 最多重试次数
     */
    private static final int RETRY_MAX_COUNT = 3;

    /**
     * 重试等待间隔
     */
    private static final int RETRY_WAIT_TIME = 2000;

    @Value("${boy235API.url}")
    private String baseUrl;

    @Value("${boy235API.token}")
    private String token;

    /**
     * gson反序列化时，用于忽略array的错误。因为有的时候字段返回为空，我们认为是可以接受的。
     */
    private GsonFailSafeArrayJsonDeserializer gsonFailSafeArrayJsonDeserializer = new GsonFailSafeArrayJsonDeserializer();

    @Autowired
    private IRemoteInterfaceRecordService remoteInterfaceRecordService;

    @Autowired
    private IRemoteInterfaceWarnSmsRecordService remoteInterfaceWarnSmsRecordService;

    /**
     * 查询xhs笔记详情
     * https://apifox.com/apidoc/shared-4936c0d3-0751-45d4-a44f-f0ccbdece532/api-9715022?pwd=WDPFEe6s
     * @param noteId
     * @return
     */
    public XhsAwemeDetailResult getXhsAwemeDetail(String noteId, Long interfaceId) {
        if (StringUtils.isBlank(noteId)) {
            return null;
        }
        Type type = new TypeToken<AwemeDetailPlatformResult>(){}.getType();
        Gson gson = new GsonBuilder().registerTypeAdapter(List.class, gsonFailSafeArrayJsonDeserializer).create();
        XhsAwemeDetailResult result = new XhsAwemeDetailResult();
        String response = RetryUtils.retry(new Callable<String>() {
            @Override
            public String call() {
                try {
                    long start = System.currentTimeMillis();
                    StringBuilder url = new StringBuilder(baseUrl).append("/xhs/api/app/note?token=").append(token).append("&note_id=").append(noteId);
                    String responseInner = HttpUtil.get(url.toString(), timeout);
                    log.info("Boy235Util查询xhs作品详情-响应耗时:{}-noteId:{},responseInner:{}", System.currentTimeMillis() - start, noteId, responseInner);
                    AwemeDetailPlatformResult temp = gson.fromJson(responseInner, type);
                    if (temp != null
                            && (Constant.containsXhsAwemeNotExistHint(StringUtil.convertUnicodeToChinese(temp.getMsg()))
                                || Constant.containsXhsAwemeNotExistHint(StringUtil.convertUnicodeToChinese(temp.get_msg())))
                    ) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                        return Constant.xhsAwemeNotExist2;
                    }
                    //如果平台那边报错再重试一次
                    if (temp == null || (temp != null && temp.getCode() != null && temp.getCode().intValue() != 0)) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                        return "";
                    }
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                    return responseInner;
                } catch (Exception e) {
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                    log.error(String.format("Boy235Util.getXhsAwemeDetail(String) error, noteId:{%s}", noteId), e);
                    return "";
                }
            }
        }, RETRY_MAX_COUNT, RETRY_WAIT_TIME);
        if (StringUtils.isBlank(response)) {
            remoteInterfaceWarnSmsRecordService.sendWarnSmsIn15mins(interfaceId,
                    new StringBuilder("noteId=").append(noteId).toString());
            return result;
        }
        if (response.equals(Constant.xhsAwemeNotExist2)) {
            return null;
        }
        try {
            AwemeDetailPlatformResult awemeDetailPlatformResult = gson.fromJson(response, type);
            result.setData(awemeDetailPlatformResult);
        } catch (Exception e) {
            log.error(String.format("Boy235Util.getXhsAwemeDetail(String) convert error, noteId:{%s}", noteId), e);
        }
        return result;
    }

    /**
     * 查询xhs笔记详情-PC
     * https://apifox.com/apidoc/shared-4936c0d3-0751-45d4-a44f-f0ccbdece532/api-161703259?pwd=WDPFEe6s
     * @param noteId
     * @return
     */
    public XhsAwemeDetailResult getXhsAwemeDetailFromPC(String noteId, Long interfaceId) {
        if (StringUtils.isBlank(noteId)) {
            return null;
        }
        Type type = new TypeToken<XhsAwemeDetailMoreApiResult>(){}.getType();
        Gson gson = new GsonBuilder().registerTypeAdapter(List.class, gsonFailSafeArrayJsonDeserializer).create();
        XhsAwemeDetailResult result = new XhsAwemeDetailResult();
        String response = RetryUtils.retry(new Callable<String>() {
            @Override
            public String call() {
                try {
                    long start = System.currentTimeMillis();
                    StringBuilder url = new StringBuilder(baseUrl).append("/xhs/api/pc/note?token=").append(token).append("&note_id=").append(noteId);
                    String responseInner = HttpUtil.get(url.toString(), timeout);
                    log.info("Boy235Util查询xhs作品详情PC-响应耗时:{}-noteId:{}", System.currentTimeMillis() - start, noteId);
                    XhsAwemeDetailMoreApiResult temp = gson.fromJson(responseInner, type);
                    if (temp != null
                            && (Constant.containsXhsAwemeNotExistHint(StringUtil.convertUnicodeToChinese(temp.getMsg()))
                                || (temp.getData() != null && Constant.containsXhsAwemeNotExistHint(StringUtil.convertUnicodeToChinese(temp.getData().getMsg())))
                            )
                    ) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                        return Constant.xhsAwemeNotExist2;
                    }
                    //如果平台那边报错再重试一次
                    if (temp == null || (temp != null && temp.getCode() != null && temp.getCode().intValue() != 0)) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                        return "";
                    }
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                    return responseInner;
                } catch (Exception e) {
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                    log.error(String.format("Boy235Util.getXhsAwemeDetailFromPC(String) error, noteId:{%s}", noteId), e);
                    return "";
                }
            }
        }, RETRY_MAX_COUNT, RETRY_WAIT_TIME);
        if (StringUtils.isBlank(response)) {
            remoteInterfaceWarnSmsRecordService.sendWarnSmsIn15mins(interfaceId, new StringBuilder("noteId=").append(noteId).toString());
            return result;
        }
        if (response.equals(Constant.xhsAwemeNotExist2)) {
            return null;
        }
        try {
            XhsAwemeDetailMoreApiResult xhsAwemeDetailMoreApiResultOrg = gson.fromJson(response, type);
            //对象转换
            if (xhsAwemeDetailMoreApiResultOrg != null && xhsAwemeDetailMoreApiResultOrg.getData() != null
                    && ! CollectionUtils.isEmpty(xhsAwemeDetailMoreApiResultOrg.getData().getItems())
                    && xhsAwemeDetailMoreApiResultOrg.getData().getItems().get(0).getNote_card() != null) {
                XhsAwemeDetailMoreApiResult.Note xhsAwemeDetailMoreApiResult = xhsAwemeDetailMoreApiResultOrg.getData().getItems().get(0).getNote_card();
                AwemeDetailPlatformResult awemeDetailPlatformResult = new AwemeDetailPlatformResult();
                AwemeDetailPlatformResult.AwemeDetail awemeDetail = awemeDetailPlatformResult.new AwemeDetail();
                //装载user对象
                AwemeDetailPlatformResult.AwemeDetail.User user = awemeDetail.new User();
                if (xhsAwemeDetailMoreApiResult.getUser() != null) {
                    user.setNickname(xhsAwemeDetailMoreApiResult.getUser().getNickname());
                    user.setImage(xhsAwemeDetailMoreApiResult.getUser().getAvatar());
                    user.setUserid(xhsAwemeDetailMoreApiResult.getUser().getUser_id());
                }
                awemeDetail.setUser(user);
                //装载笔记对象
                List<AwemeDetailPlatformResult.AwemeDetail.Note> noteList = new ArrayList<>();
                AwemeDetailPlatformResult.AwemeDetail.Note note = awemeDetail.new Note();
                note.setDesc(xhsAwemeDetailMoreApiResult.getDesc());
                note.setTitle(xhsAwemeDetailMoreApiResult.getTitle());
                note.setTime(xhsAwemeDetailMoreApiResult.getTime());
                note.setLast_update_time(xhsAwemeDetailMoreApiResult.getLast_update_time());
                note.setType(xhsAwemeDetailMoreApiResult.getType());
                note.setGoodsId(xhsAwemeDetailMoreApiResult.getGoodsId());
                note.setWidgets_context(xhsAwemeDetailMoreApiResult.getWidgets_context());
                if (xhsAwemeDetailMoreApiResult.getInteract_info() != null) {
                    note.setCollected(xhsAwemeDetailMoreApiResult.getInteract_info().getCollected());
                    note.setCollected_count(xhsAwemeDetailMoreApiResult.getInteract_info().getCollected_count());
                    note.setLiked_count(xhsAwemeDetailMoreApiResult.getInteract_info().getLiked_count());
                    note.setComments_count(xhsAwemeDetailMoreApiResult.getInteract_info().getComment_count());
                    note.setShared_count(xhsAwemeDetailMoreApiResult.getInteract_info().getShare_count());
                }
                if (! CollectionUtils.isEmpty(xhsAwemeDetailMoreApiResult.getImage_list())) {
                    List<AwemeDetailPlatformResult.AwemeDetail.Note.Image> imageList = new ArrayList<>();
                    note.setImages_list(imageList);
                    for (XhsAwemeDetailMoreApiResult.Note.Image image : xhsAwemeDetailMoreApiResult.getImage_list()) {
                        AwemeDetailPlatformResult.AwemeDetail.Note.Image image1 = note.new Image();
                        image1.setFileid(image.getFile_id());
                        image1.setHeight(image.getHeight());
                        image1.setWidth(image.getWidth());
                        image1.setUrl(image.getUrl());
                        image1.setTrace_id(image.getTrace_id());
                        if(! CollectionUtils.isEmpty(image.getInfo_list())){
                            for(XhsAwemeDetailMoreApiResult.Note.Image.CoverInfo infoList : image.getInfo_list()){
                                if(Constant.CRD_WM_WEBP.equals(infoList.getImage_scene())){
                                    image1.setOriginal(infoList.getUrl());
                                }
                            }
                        }
                        if(image.getStream() != null && !CollectionUtils.isEmpty(image.getStream().getH264())){
                            AwemeDetailPlatformResult.AwemeDetail.Note.Image.LivePhoto livePhoto = image1.new LivePhoto();
                            AwemeDetailPlatformResult.AwemeDetail.Note.Image.LivePhoto.Media media = livePhoto.new Media();
                            AwemeDetailPlatformResult.AwemeDetail.Note.Image.LivePhoto.Media.Stream stream = media.new Stream();
                            List<AwemeDetailPlatformResult.AwemeDetail.Note.Image.LivePhoto.Media.Stream.H264> h264List = new ArrayList<>();
                            for (XhsAwemeDetailMoreApiResult.Note.Image.Stream.H264 h264 : image.getStream().getH264()) {
                                AwemeDetailPlatformResult.AwemeDetail.Note.Image.LivePhoto.Media.Stream.H264 h264_1 = stream.new H264();
                                h264_1.setMaster_url(h264.getMaster_url());
                                h264List.add(h264_1);
                            }
                            stream.setH264(h264List);
                            media.setStream(stream);
                            livePhoto.setMedia(media);
                            image1.setLive_photo(livePhoto);
                        }
                        imageList.add(image1);
                    }
                }
                AwemeDetailPlatformResult.AwemeDetail.Note.ShareInfo shareInfo = note.new ShareInfo();
                note.setShare_info(shareInfo);

                //笔记文案
                if (StringUtils.isNotBlank(xhsAwemeDetailMoreApiResult.getTitle())) {
                    shareInfo.setTitle(xhsAwemeDetailMoreApiResult.getTitle());
                }

                noteList.add(note);
                awemeDetail.setNote_list(noteList);
                awemeDetail.setUser(user);

                List<AwemeDetailPlatformResult.AwemeDetail> awemeDetailList = new ArrayList<>();
                awemeDetailList.add(awemeDetail);
                awemeDetailPlatformResult.setData(awemeDetailList);
                awemeDetailPlatformResult.setCode(xhsAwemeDetailMoreApiResultOrg.getCode());
                awemeDetailPlatformResult.setMsg(xhsAwemeDetailMoreApiResultOrg.getMsg());
                result.setData(awemeDetailPlatformResult);
            }
        } catch (Exception e) {
            log.error(String.format("Boy235Util.getXhsAwemeDetailFromPC(String) convert error, noteId:{%s}", noteId), e);
        }
        return result;
    }


    public static void main(String[] args) {
        String response = HttpUtil.get("http://ttt.boy235.com/sf/auth/info/?token=UjMyux1v7g80pts2");
        //String response = HttpUtil.get("http://ttt.boy235.com/xhs/api/app/search/note/v2?keyword=杭州&token=UjMyux1v7g80pts2&page=1&sort=general");
        //String response = HttpUtil.get("http://ttt.boy235.com/xhs/api/app/note?token=UjMyux1v7g80pts2&note_id=66b479c8000000001e01e1ae");
        //String response = HttpUtil.get("http://ttt.boy235.com/xhs/api/app/user/note?token=UjMyux1v7g80pts2&user_id=61a750c8000000001000cc19");
        //String response = HttpUtil.get("http://ttt.boy235.com/xhs/api/app/user/v2?token=UjMyux1v7g80pts2&user_id=61a750c8000000001000cc19");
        //String response = HttpUtil.get("http://ttt.boy235.com/xhs/api/pc/note?token=UjMyux1v7g80pts2&note_id=65eefc2700000000120219c2");
        System.out.println(response);
    }
}
